<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="queryParams.type"
            class="vt-select"
            placeholder="请选择类型"
            clearable
          >
            <el-option
              v-for="orderType in configStore.getOrderTypes"
              :key="orderType.value"
              :label="orderType.label"
              :value="orderType.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            class="vt-select"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="orderStatus in configStore.getOrderStatuses"
              :key="orderStatus.value"
              :label="orderStatus.label"
              :value="orderStatus.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="袋型" prop="bagType">
          <VtSelect
            v-model="queryParams.bagType"
            class="vt-select"
            type="bagType"
            :filter-type="2"
            placeholder="请选择袋型"
          />
        </el-form-item>
        <el-form-item label="材质" prop="material">
          <VtSelect
            v-model="queryParams.material"
            class="vt-select"
            type="material"
            show-name-only
            placeholder="请选择材质"
          />
        </el-form-item>
        <el-form-item label="复合工艺" prop="compositeType">
          <VtSelect
            v-model="queryParams.compositeType"
            class="vt-select"
            type="compositeType"
            show-name-only
            placeholder="请选择复合工艺"
          />
        </el-form-item>
        <el-form-item label="印刷颜色" prop="surfaceFee">
          <VtSelect
            v-model="queryParams.surfaceFee"
            class="vt-select"
            type="surfaceFee"
            show-name-only
            placeholder="请选择印刷颜色"
          />
        </el-form-item>
        <el-form-item label="配件" prop="accessory">
          <VtSelect
            v-model="queryParams.accessory"
            class="vt-select"
            type="accessory"
            show-name-only
            placeholder="请选择配件"
          />
        </el-form-item>
        <el-form-item label="创建人" prop="createdId">
          <el-select
            v-model="queryParams.createdId"
            class="vt-select"
            placeholder="请选择创建人"
            clearable
            filterable
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.nickname || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
          <el-popover
            placement="bottom"
            :width="200"
            trigger="click"
            popper-class="notification-popover"
          >
            <template #reference>
              <el-button size="default" :icon="Bell" circle></el-button>
            </template>
            <div class="notification-settings">
              <h4>通知设置</h4>
              <div class="setting-item">
                <span>声音提醒</span>
                <el-switch v-model="soundEnabled" />
              </div>
              <div class="setting-item">
                <span>桌面通知</span>
                <el-switch v-model="notificationEnabled" />
              </div>
              <div
                v-if="vtOrderStore.notificationEnabled && !hasNotificationPermission"
                class="setting-tip"
              >
                <el-alert type="warning" :closable="false" size="small" show-icon>
                  <span>需要授权通知权限</span>
                  <el-button
                    type="primary"
                    link
                    size="small"
                    @click="requestNotificationPermission"
                  >
                    请求权限
                  </el-button>
                </el-alert>
              </div>
            </div>
          </el-popover>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <el-table :data="pageData" style="width: 100%" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column width="55" align="center" prop="id" label="单号" />
        <el-table-column key="type" label="类型" prop="type" min-width="70" align="center">
          <template #default="scope">
            {{ configStore.getOrderTypeLabel(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column key="status" label="状态" prop="status" min-width="90" align="center">
          <template #default="scope">
            <el-tag :type="configStore.getOrderStatusType(scope.row.status)">
              {{ configStore.getOrderStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column key="bagType" label="袋型" prop="bagType" min-width="110" align="center">
          <template #default="{ row }">
            <span>{{ formatBagType(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column key="size" label="尺寸(mm)" min-width="120" align="center">
          <template #default="{ row }">
            <span>{{ formatSize(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          key="material"
          label="材质"
          prop="material"
          min-width="110"
          align="center"
        />
        <el-table-column
          key="compositeType"
          label="复合工艺"
          prop="compositeType"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="surfaceFee"
          label="印刷颜色"
          prop="surfaceFee"
          min-width="100"
          align="center"
        />
        <el-table-column
          key="accessory"
          label="配件"
          prop="accessory"
          min-width="100"
          align="center"
        />
        <el-table-column
          key="thickness"
          label="单面厚度(丝)"
          prop="thickness"
          min-width="110"
          align="center"
        />
        <el-table-column
          key="quantity1"
          label="数量"
          prop="quantity1"
          min-width="80"
          align="center"
        />
        <el-table-column
          key="weight1"
          label="重量(kg)"
          prop="weight1"
          min-width="80"
          align="center"
        />
        <el-table-column
          key="price1"
          label="总价(元)"
          prop="price1"
          min-width="100"
          align="center"
        />
        <el-table-column
          key="createdId"
          label="创建人"
          prop="createdId"
          min-width="80"
          align="center"
        >
          <template #default="scope">
            <UserLabel :model-value="scope.row.createdId" />
          </template>
        </el-table-column>
        <el-table-column
          key="handleId"
          label="处理人"
          prop="handleId"
          min-width="80"
          align="center"
        >
          <template #default="scope">
            <UserLabel :model-value="scope.row.handleId" />
          </template>
        </el-table-column>
        <el-table-column
          key="l"
          label="创建时间"
          prop="createTime"
          min-width="160"
          align="center"
        />
        <el-table-column fixed="right" label="操作" min-width="80">
          <template #default="scope">
            <el-button
              v-hasPerm="['vt:vt-order:handle']"
              type="primary"
              size="small"
              link
              @click="handleEdit(scope.row.id, 2)"
            >
              <template #icon>
                <Edit />
              </template>
              处理
            </el-button>
            <br />
            <el-button
              v-hasPerm="['vt:vt-order:edit']"
              type="primary"
              size="small"
              link
              @click="handleEdit(scope.row.id, 1)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>
  </div>
</template>

<script setup>
defineOptions({
  name: "VtOrder",
  inheritAttrs: false,
});

import { onMounted, reactive, ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { Bell } from "@element-plus/icons-vue";
import { useConfigStore } from "@/store/modules/config.store.js";
import { useUserCacheStore } from "@/store/modules/user-cache.store.js";
import { useVtOrderStore } from "@/store/modules/vt-order.store.js";

import VtOrderAPI from "@/api/vt/vt-order.js";

const configStore = useConfigStore();
const vtOrderStore = useVtOrderStore();
const userCacheStore = useUserCacheStore();

const router = useRouter();
const queryFormRef = ref();

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const orderList = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  createdId: undefined,
});

// 报价单表格数据
const pageData = computed(() => orderList.value);

// 用户列表数据
const userList = computed(() => userCacheStore.getAllUsers);

// 通知权限状态
const hasNotificationPermission = ref(false);

// 声音通知开关的计算属性
const soundEnabled = computed({
  get: () => vtOrderStore.soundEnabled,
  set: (value) => {
    if (value !== vtOrderStore.soundEnabled) {
      vtOrderStore.toggleSound();
    }
  },
});

// 桌面通知开关的计算属性
const notificationEnabled = computed({
  get: () => vtOrderStore.notificationEnabled,
  set: (value) => {
    if (value !== vtOrderStore.notificationEnabled) {
      vtOrderStore.toggleNotification();
      if (value) {
        checkNotificationPermission();
      }
    }
  },
});

// 检查通知权限
function checkNotificationPermission() {
  if ("Notification" in window) {
    hasNotificationPermission.value = Notification.permission === "granted";
  }
}

// 请求通知权限
function requestNotificationPermission() {
  if ("Notification" in window) {
    Notification.requestPermission().then((permission) => {
      hasNotificationPermission.value = permission === "granted";
    });
  }
}

/** 查询报价单 */
function handleQuery() {
  loading.value = true;
  VtOrderAPI.getPage(queryParams)
    .then((data) => {
      orderList.value = data.list || [];
      total.value = data.total || 0;
    })
    .catch((error) => {
      console.error("获取报价单列表失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置报价单查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 编辑报价单 */
function handleEdit(id, t) {
  router.push({ name: "VtOrderForm", query: { id, t } });
}

/** 格式化尺寸显示 */
function formatSize(row) {
  const { l, w, h } = row;

  // 如果没有任何尺寸数据
  if (!l && !w && !h) {
    return "-";
  }

  // 只有 l（卷膜情况）
  if (l && (!w || w === 0) && (!h || h === 0)) {
    return `${l}`;
  }

  // 没有 h 的情况：显示 l*w
  if (l && w && (!h || h === 0)) {
    return `${l}*${w}`;
  }

  // 完整的 l*w+h 格式
  if (l && w && h) {
    return `${l}*${w}+${h}`;
  }

  return "-";
}

/** 格式化袋型显示 */
function formatBagType(row) {
  const { bagType, remark3 } = row;

  // 如果没有任何尺寸数据
  if (bagType) {
    return bagType;
  }
  try {
    if (remark3) {
      return JSON.parse(remark3).subType;
    }
  } catch {
    return "-";
  }
}

// 监听store中的total变化，当total变化时刷新列表
watch(
  () => vtOrderStore.total,
  (newTotal, oldTotal) => {
    // 只有在total真正变化且不是初始化时才刷新
    if (newTotal !== oldTotal && oldTotal !== undefined) {
      handleQuery();
    }
  }
);

// 监听store中的状态统计变化，当状态变化时刷新列表
watch(
  () => vtOrderStore.getStatusCounts,
  (newStatusCounts, oldStatusCounts) => {
    // 只有在状态统计真正变化且不是初始化时才刷新
    if (oldStatusCounts && JSON.stringify(newStatusCounts) !== JSON.stringify(oldStatusCounts)) {
      handleQuery();
    }
  },
  { deep: true }
);

onMounted(() => {
  // 加载通知设置
  vtOrderStore.loadNotificationSettings();
  // 检查通知权限
  checkNotificationPermission();

  // 加载用户数据
  userCacheStore.loadUsers();

  // 初始查询
  handleQuery();
});

// 注意：自动刷新现在在全局级别处理，无需在页面级别启动/停止
</script>
<style scoped lang="scss">
.vt-select {
  width: 100%;
  min-width: 150px;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
}

.notification-settings {
  h4 {
    margin: 0 0 12px 0;
    font-size: 14px;
    color: #303133;
  }

  .setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    span {
      font-size: 13px;
      color: #606266;
    }
  }

  .setting-tip {
    margin-top: 8px;
  }
}
</style>
